<template>
  <d2-container>
    <div>
      <div style="background-color: rgba(255, 255, 255, 0.9)">
        <!-- // 首页 考核类型，考核名称，考核对象 -->
        <div class="formsize">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <div style="width: 50%; margin-left: 25%">
              <el-form-item label="考核类型">
                <el-select v-model="ruleForm.type" placeholder="请选择考核类型">
                  <el-option label="部门考核" value="部门考核"></el-option>
                  <el-option label="个人考核" value="个人考核"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="考核名称">
                <el-input v-model="ruleForm.templateName"></el-input>
              </el-form-item>
              <el-form-item label="考核对象">
                <el-select v-model="CurrentDepartment" placeholder="请选择考核对象">
                  <el-option v-for="item in allDepartment" :key="item.name" :label="item.name"
                    :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- // 设置考核项弹出框内容 -->
            <!-- Table -->
            <el-button style="background-color: #0099cc; color: white" type="text"
              @click="dialogTableVisibleOpen">
              设置考核项</el-button>
            <el-button style="background-color: #0099cc; color: white" @click="dialogTableVisibleClear"
              type="text">清空考核项</el-button>

            <el-dialog title="添加考核项" :visible.sync="dialogTableVisible">

              <el-form :model="form">
                <el-form-item label="选择部门" :label-width="formLabelWidth">
                  <el-select v-model="form.value1" @change="selectDepartment" placeholder="请选择考核部门">
                    <el-option v-for="item in form.region1" :key="item.name" :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="选择指标" :label-width="formLabelWidth">
                  <el-select v-model="form.value2" placeholder="请选择部门指标">
                    <el-option v-for="item in form.region2" :key="item" :label="item" :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-button style="background-color:#0099CC;color:white" type="button"
                  @click="open(form.region2)">查找</el-button>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogTableVisibleCancel">取 消</el-button>
                <el-button type="primary" @click="dialogTableVisibleConfirm">确 定</el-button>
              </div>

              <el-table :data="assessStandardlist">
                <el-table-column property="deptString" label="所属部门" width="150">
                </el-table-column>
                <el-table-column property="name" label="考核项" width="150"></el-table-column>
                <el-table-column property="targetedValue" label="指标值" width="200"></el-table-column>
                <el-table-column property="weight" label="权重" width="200"></el-table-column>

              </el-table>

            </el-dialog>

            <!-- // 首页考核项内容展示 -->
            <!-- table -->
            <el-table ref="multipleTable" :data="assessStandardlist" tooltip-effect="dark"
              style="width: 100%" @selection-change="handleSelectionChange" max-height="400">
              <el-table-column type="selection" width="55"> </el-table-column>

              <el-table-column prop="ifpaName" label="指标名称" width="80">
                <template slot-scope="scope">{{
              scope.row.ifpaName
            }}</template>
              </el-table-column>
              <el-table-column prop="name" label="考核项" width="120">
                <template slot-scope="scope">{{
              scope.row.name
            }}</template>
              </el-table-column>
              <el-table-column prop="targetedValue" label="指标值" width="80">
                <template slot-scope="scope">{{
              scope.row.targetedValue
            }}</template>
              </el-table-column>
              <el-table-column prop="weight" label="指标权重" width="90">
                <template slot-scope="scope">{{
              scope.row.weight
            }}</template>
              </el-table-column>
              <el-table-column prop="type" label="设置考核评分人" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-table :data="scope.row.assessment" :show-header="false">
                    <el-table-column show-overflow-tooltip prop="rater">
                    </el-table-column>
                    <el-table-column>
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.raterUserWeightId" size="mini"></el-input>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button type="primary" @click="addRater(scope.row,scope.$index)">添加评分人
                  </el-button>
                  <!-- // 首页考核项内容展示中的考核评分人添加弹出框列表 -->
                  <!-- Form -->
                  <el-dialog title="部门成员" :visible.sync="dialogFormVisible">
                    <el-form :model="form1">
                      <el-form-item label="选择评分人" :label-width="formLabelWidth">
                        <el-select v-model="form1.value2" placeholder="请选择部门评分人">
                          <el-option v-for="item in form1.region1" :key="item.name"
                            :label="item.name" :value="item.name">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-button type="primary" @click="addRaterConfirm">确 定</el-button>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                      <el-button type="primary" @click="dialogFormVisibleOut">退出</el-button>
                    </div>
                  </el-dialog>
                </template>
              </el-table-column>
              <!-- // 删除考核项事件按钮 -->
              <el-table-column label="操作" width="210">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="operition" label="操作" show-overflow-tooltip>
        </el-table-column> -->
            </el-table>
            <center>
              <div class="button">
                <el-button @click="submit" type="primary">提交</el-button>
                <el-button @click="Reset" type="primary">重置</el-button>
                <el-button @click="create" type="primary">返回</el-button>
              </div>
            </center>
          </el-form>
        </div>
      </div>
    </div>
  </d2-container>
</template>
<style scoped>
  .formsize {
    background-color: white;
    width: 70%;
    height: 100%;
    margin: auto;
    padding-top: 50px;
    padding-bottom: 80px;
  }

  .button {
    background-color: white;
    margin-top: 100px;
    margin-bottom: 100px;
    width: 70%;
    margin: auto;
    padding-top: 50px;
    padding-bottom: 80px;
  }
</style>

<script>
export default {
  data () {
    return {
      ruleForm: {},
      showHeader: false,
      rules: {
        name: [{
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 5,
          message: '长度在 3 到 5 个字符',
          trigger: 'blur'
        }
        ]
      },
      allDepartment: [],
      CurrentDepartment: '',
      // 考核项展示属性
      tableData: [],
      multipleSelection: [],
      // 弹框内容
      gridData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: '',
        region1: [],
        value1: '',
        region2: [],
        value2: '',
        region3: [],
        value3: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      form1: {
        name: '',
        region1: [],
        assessStandard: [],
        value1: '',
        value2: '',
        index: ''
      },
      formLabelWidth: '120px',
      templateid: 0,
      assessStandardlist: [],
      assessItem: {
        dept: null
      },
      assessStandard: {
        limit: 10,
        currentPage: 1,
        data: {
          ifpaName: ''
        }
      },
      dept: {
        id: null,
        name: '',
        leader: ''
      },
      appraisalTemplate: {
        id: null,
        type: '',
        templateName: '',
        department: '',
        departmentId: '',
        templateAssess: []

      },
      newTemplate: {
        type: '',
        templateName: '',
        department: '',
        departmentId: '',
        templateAssess: [],
        raterUser: []
      }

    }
  },
  created () {
    // 查询后端信息
    this.Departments()
    this.templateid = this.$route.query.id
    if (this.templateid > 0) {
      this.getdata()
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 加载页面后获取所有部门
    Departments () {
      this.$request({
        url: 'dept/findAllDept',
        method: 'post',
        data: null
      }).then(res => {
        this.allDepartment = res
      }).catch(err => {
        console.log(err)
      })
    },
    // 考核项方法
    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 从模板列表页面调过来获取模板信息
    getdata () {
      this.$request({
        url: 'AppraisalTemplate/findTemplate',
        method: 'get',
        params: {
          id: this.templateid
        }
      })
        .then((res) => {
          this.ruleForm = res
          this.CurrentDepartment = this.ruleForm.department
          const arr = []
          for (const key in res.templateAssess) {
            if (Object.hasOwnProperty.call(res.templateAssess, key)) {
              const element = res.templateAssess[key]
              arr[key] = element.assessItem
              arr[key].assessment = element.raterUser
            }
          }
          this.assessStandardlist = arr

          // 根据部门id查找部门所有用户
          this.$request({
            url: 'user/findAllByDept',
            method: 'post',
            data: this.ruleForm.departmentId
          }).then(res => {
            this.form1.region1 = res
          }).catch(err => {
            console.log(err)
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 清空考核项
    dialogTableVisibleClear () {
      this.assessItem.dept = ''
      this.form.value2 = ''
      this.assessStandard.data.ifpaName = ''
      this.assessStandardlist = null
    },
    // 设置考核项的方法
    dialogTableVisibleOpen () {
      this.dialogTableVisible = true
      this.$request({
        url: 'dept/findAllDept',
        method: 'post',
        data: null
      }).then(res => {
        this.form.region1 = res
      }).catch(err => {
        console.log(err)
      })
    },
    // 设置考核项中选择部门后的change方法
    selectDepartment () {
      this.assessItem.dept = ''
      this.form.value2 = ''
      this.assessItem.dept = this.form.value1
      this.$request({
        url: 'item/findByDept',
        method: 'post',
        data: this.assessItem
      }).then(res => {
        // 数组去重
        var arr0 = []
        for (const key in res) {
          if (Object.hasOwnProperty.call(res, key)) {
            const element = res[key].ifpaName
            arr0[key] = element
          }
        }
        var List = arr0
        var List2 = []
        for (var i = 0; i < List.length; i++) {
          if (List.indexOf(List[i]) === i) {
            List2.push(List[i])
          }
        }
        this.form.region2 = List2
      }).catch(err => {
        console.log(err)
      })
    },
    // 选择指标后的查找按钮的方法
    open () {
      this.assessStandard.data.ifpaName = this.form.value2
      if (this.assessStandard.data.ifpaName !== '') {
        this.$request({
          url: 'item/findAllAssessItem',
          method: 'post',
          data: this.assessStandard
        })
          .then((res) => {
            this.assessStandardlist = res.list
            // 创建map，key为部门名，value为领导名
            const map = new Map()
            for (const key in this.allDepartment) {
              if (Object.hasOwnProperty.call(this.allDepartment, key)) {
                const dept = this.allDepartment[key]
                map.set(dept.name, dept.leaderName)
              }
            }
            // 遍历查到的考核项数组
            for (const key in this.assessStandardlist) {
              if (Object.hasOwnProperty.call(this.assessStandardlist, key)) {
                const element = this.assessStandardlist[key]
                const arr = []
                arr.push({
                  rater: map.get(element.deptString),
                  raterUserWeightId: 100,
                  assessId: element.id,
                  weight: element.weight
                })
                // arr[arr.length()] = { rater: map.get(this.CurrentDepartment), raterUserWeightId: 100 }
                element.assessment = arr
              }
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
    // 设置考核项弹出框中的确认按钮后的方法
    dialogTableVisibleConfirm () {
      this.dialogTableVisible = false
      this.dept.id = this.form.value1
      this.assessItem.dept = ''
      this.$request({
        url: 'dept/findOne',
        method: 'post',
        data: this.dept
      }).then(res => {
        this.CurrentDepartment = res.name
        // 根据部门id查找部门所有用户
        this.$request({
          url: 'user/findAllByDept',
          method: 'post',
          data: this.dept.id
        }).then(res => {
          this.form1.region1 = res
        }).catch(err => {
          console.log(err)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 添加评分人按钮
    addRater (assessStandard, index) {
      this.dialogFormVisible = true
      this.form1.assessStandard = assessStandard
      this.form1.index = index
    },
    // 弹出框 确认按钮事件
    addRaterConfirm () {
      this.dialogFormVisible = true
      this.assessStandardlist[this.form1.index].assessment.push({
        rater: this.form1.value2,
        raterUserWeightId: 100,
        assessId: this.assessStandardlist[this.form1.index].id,
        weight: this.assessStandardlist[this.form1.index].weight
      })
      if (this.assessStandardlist[this.form1.index].assessment.length > 1) {
        const i = 100 / this.assessStandardlist[this.form1.index].assessment.length
        for (const key in this.assessStandardlist[this.form1.index].assessment) {
          if (Object.hasOwnProperty.call(this.assessStandardlist[this.form1.index].assessment, key)) {
            const element = this.assessStandardlist[this.form1.index].assessment[key]
            element.raterUserWeightId = i
          }
        }
      }
    },
    // 选择评分人退出按钮
    dialogFormVisibleOut () {
      this.form1.value2 = ''
      this.dialogFormVisible = false
    },
    // 跳转新建模板页面
    create () {
      this.$router.push('/templatelist')
    },
    // 弹出框取消按钮
    dialogTableVisibleCancel () {
      this.dialogTableVisible = false
    },
    // 删除考核项按钮
    handleDelete (index, row) {
      var removeWeight = this.assessStandardlist[index].weight
      this.assessStandardlist.splice(index, 1)
      var weightreal = Math.round((removeWeight / this.assessStandardlist.length) * 10) / 10
      for (const key in this.assessStandardlist) {
        if (Object.hasOwnProperty.call(this.assessStandardlist, key)) {
          const element = this.assessStandardlist[key]
          element.weight = Math.round((element.weight + weightreal) * 100) / 100
        }
      }
    },
    // 重置按钮
    Reset () {
      this.dialogTableVisibleClear()
      this.ruleForm = {}
      this.CurrentDepartment = ''
      this.templateid = ''
      this.form1 = {
        name: '',
        region1: [],
        assessStandard: [],
        value1: '',
        value2: '',
        index: ''
      }
    },
    // 最后的新增提交的按钮方法
    submit () {
      this.newTemplate.type = this.ruleForm.type
      this.newTemplate.templateName = this.ruleForm.templateName
      this.newTemplate.department = this.CurrentDepartment
      this.newTemplate.id = this.ruleForm.id
      var a = 0
      var arr1 = []
      // 遍历查询出的考核项得到每一个对象
      for (const key in this.assessStandardlist) {
        if (Object.hasOwnProperty.call(this.assessStandardlist, key)) {
          const element = this.assessStandardlist[key]
          const arr = []
          arr[key] = {
            assessId: element.id
          }
          // 提取每一个考核项对象得id封装到数组中再封装进newTemplate中
          this.newTemplate.templateAssess[key] = arr[key]
          // 遍历每一个考核项中添加得考核人信息封装进数组中再封装进newTemplate
          for (const key1 in element.assessment) {
            if (Object.hasOwnProperty.call(element.assessment, key1)) {
              const element1 = element.assessment[key1]
              arr1[a] = element1
              this.newTemplate.raterUser[a] = arr1[a]
              a++
            }
          }
        }
      }
      this.$request({
        url: 'AppraisalTemplate/insertNewTemplate',
        method: 'post',
        data: this.newTemplate
      }).then(res => {
        this.$message('提交成功')
        this.$router.push('/templatelist')
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
